/* **************************************************
 Copyright (c) 2012, University of Cambridge
 Neal Lathia, neal.lathia@cl.cam.ac.uk
 Kiran Rachuri, kiran.rachuri@cl.cam.ac.uk

This library was developed as part of the EPSRC Ubhave (Ubiquitous and
Social Computing for Positive Behaviour Change) Project. For more
information, please visit http://www.emotionsense.org

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ************************************************** */

package com.ubhave.sensormanager.sensors.pull;

import com.ubhave.sensormanager.BuildConfig;
import com.ubhave.sensormanager.ESException;
import com.ubhave.sensormanager.config.pull.LocationConfig;
import com.ubhave.sensormanager.data.SensorData;
import com.ubhave.sensormanager.data.pull.LocationData;
import com.ubhave.sensormanager.process.pull.LocationProcessor;
import com.ubhave.sensormanager.sensors.SensorUtils;
import com.ubhave.sensormanager.utils.LogUtil;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.app.Context;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventPublishInfo;
import ohos.location.Location;
import ohos.location.Locator;
import ohos.location.LocatorCallback;
import ohos.location.RequestParam;
import ohos.rpc.RemoteException;

import java.util.ArrayList;
import java.util.List;

public class LocationSensor extends AbstractPullSensor {
    private static final String TAG = "LocationSensor";
    private static final String[] LOCATION_PERMISSIONS = new String[]{
            "ohos.permission.LOCATION",
            "ohos.permission.LOCATION_IN_BACKGROUND"
    };

    private volatile static LocationSensor locationSensor;
    private static Object lock = new Object();

    private Locator locationManager;
    private List<Location> locationList;
    private LocatorCallback locListener;
    private LocationData locationData;

    public static LocationSensor getSensor(final Context context) throws ESException {
        LocationSensor localLocationSensor = locationSensor;
        if (localLocationSensor == null) {
            synchronized (lock) {
                localLocationSensor = locationSensor;
                if (localLocationSensor == null) {
                    if (anyPermissionGranted(context, LOCATION_PERMISSIONS)) {
                        locationSensor = localLocationSensor = new LocationSensor(context);
                    } else {
                        throw new ESException(ESException.PERMISSION_DENIED, SensorUtils.SENSOR_NAME_LOCATION);
                    }
                }
            }
        }
        return locationSensor;
    }

    private LocationSensor(Context context) {
        super(context);
        locationManager = new Locator(context);
        locListener = new LocatorCallback() {

            @Override
            public void onLocationReport(Location location) {
                LogUtil.loge("===onLocationReport: " + location);
                if (isSensing) {
                    locationList.add(location);
                    sendBroadCast(location);
                }

            }

            @Override
            public void onStatusChanged(int type) {
                LogUtil.loge("===onStatusChanged: " + type);
//                Locator.SESSION_START  2
//                Locator.SESSION_STOP   3
            }

            @Override
            public void onErrorReport(int type) {
                LogUtil.loge("===onErrorReport" + type);
//                Locator.ERROR_PERMISSION_NOT_GRANTED  256
//                Locator.ERROR_SWITCH_UNOPEN   257
            }
        };
    }

    private void sendBroadCast(Location location) {
        /*try {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withBundleName(BuildConfig.PACKAGE_NAME).withAction("default.Location").build();
            intent.setOperation(operation);
            if (null == location) {
                intent.setParam("hasData", false);
            } else {
                intent.setParam("hasData", true);
                intent.setParam("latitude", location.getLatitude());
                intent.setParam("longitude", location.getLongitude());
                intent.setParam("accuracy", location.getAccuracy());
                intent.setParam("direction", location.getDirection());
                intent.setParam("speed", location.getSpeed());
                intent.setParam("timeMillis", location.getTimeStamp());
            }
            CommonEventData eventData = new CommonEventData(intent);
            CommonEventPublishInfo info = new CommonEventPublishInfo();
            info.setSubscriberPermissions(new String[]{BuildConfig.PACKAGE_NAME});
            CommonEventManager.publishCommonEvent(eventData, info);
        } catch (RemoteException e) {
            LogUtil.loge(getLogTag(), "publishCommonEvent occur exception.");
        }*/
    }

    public String getLogTag() {
        return TAG;
    }

    public int getSensorType() {
        return SensorUtils.SENSOR_TYPE_LOCATION;
    }

    protected boolean startSensing() {
        locationList = new ArrayList<Location>();
        try {
            String accuracyConfig = (String) sensorConfig.getParameter(LocationConfig.ACCURACY_TYPE);
            if ((accuracyConfig != null) && (accuracyConfig.equals(LocationConfig.LOCATION_ACCURACY_FINE))) {
                //ohos中不再区分网络定位和GPS定位
                RequestParam requestParam = new RequestParam(RequestParam.PRIORITY_ACCURACY, 500, 0);
                requestParam.setMaxAccuracy(1000);
                locationManager.startLocating(requestParam, locListener);
            } else {
                RequestParam requestParam = new RequestParam(RequestParam.PRIORITY_LOW_POWER, 500, 0);
                requestParam.setMaxAccuracy(1000);
                locationManager.startLocating(requestParam, locListener);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    protected void stopSensing() {
        if (locationManager != null) {
            locationManager.stopLocating(locListener);
        }
    }

    protected SensorData getMostRecentRawData() {
        return locationData;
    }

    protected void processSensorData() {
        LocationProcessor processor = (LocationProcessor) getProcessor();
        locationData = processor.process(pullSenseStartTimestamp, locationList, sensorConfig.clone());
    }
}
